﻿using MailKit.Net.Smtp;
using MimeKit;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;

namespace BCCommon
{
    /// <summary>
    /// 邮件工具
    /// </summary>
    public class EmailHelper
    {
        private string smtpHosting { get; set; }
        private bool enableSSL { get; set; }
        private int port { get; set; } = 25;
        private string fromUser { get; set; }
        private string fromUserPassword { get; set; }
        public EmailHelper(string smtpHosting, bool enableSSL, int port, string fromUser, string fromUserPassword)
        {
            this.smtpHosting = smtpHosting;
            this.enableSSL = enableSSL;
            this.port = port;
            this.fromUser = fromUser;
            this.fromUserPassword = fromUserPassword;
        }
        public bool SendMail(string title, string[] toUserEmail, string body, bool isHtml = true)
        {
            MimeMessage mail = new MimeMessage();

            mail.From.Add(new MailboxAddress("exception",fromUser));
            foreach (string item in toUserEmail)
            {
                mail.To.Add(new MailboxAddress(item.Replace("@xablackcoffee.com", ""), item));
            }
            mail.Subject = title.Replace("\r\n", " ").Replace("\n", " ");

            var bodyBuilder = new BodyBuilder();
            bodyBuilder.TextBody = body;
            mail.Body = bodyBuilder.ToMessageBody();

            try
            {
#if RELEASE
                using (var client = new SmtpClient())
                {
                    client.ServerCertificateValidationCallback = (s, c, h, e) => true;
                    //smtp服务器，端口，是否开启ssl
                    client.Connect(smtpHosting, 465, true);
                    client.Authenticate(fromUser, fromUserPassword);
                    client.Send(mail);
                    client.Disconnect(true);
                }
#endif
                return true;
            }
            catch (Exception ex)
            {
                string str = JsonConvert.SerializeObject(ex);
                DirectoryInfo directoryInfo = new DirectoryInfo(Directory.GetCurrentDirectory());
                string path = Path.Combine(directoryInfo.FullName, "MailExceptionLog", DateTime.Now.ToString("yyyy-MM-dd"));
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }
                FileInfo fileInfo = new FileInfo(Path.Combine(path, "MailExceptionLog.txt").ToString());
                Console.WriteLine("*****************************************");
                Console.WriteLine(str);
                Console.WriteLine(path);

                if (!fileInfo.Exists)
                {
                    using (StreamWriter sw = fileInfo.CreateText())
                    {
                        sw.WriteLine("*****************************************");
                        sw.WriteLine("当前时间：{0}", DateTime.Now.ToString());
                        sw.WriteLine("{0}", str);
                    }
                }
                else
                {
                    using (StreamWriter sw = fileInfo.AppendText())
                    {
                        sw.WriteLine("*****************************************");
                        sw.WriteLine("当前时间：{0}", DateTime.Now.ToString());
                        sw.WriteLine("{0}", str);
                    }
                }
                return false;
            }
        }
    }
}
